<script setup>
import { ElMessage } from 'element-plus';
import Layer from "@/components/layer/index.vue";
import { defineProps, ref, defineEmits, onMounted } from 'vue'
import { addAPI, updateAPI } from '@/api/wedding/articleInfo'
import { upload } from '@/api/wedding/attachInfo'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';
import { dicVals } from '@/api/common';


// 使用defineEmits来接收来自父组件的方法
const emit = defineEmits(['getTableData'])
// 声明props
const props = defineProps({
  layer: {
    type: Object,
    default: () => {
      return {
        show: false,
        title: '',
        showButton: true
      }
    }
  }
});

/************************************定义变量************************************************/
const ruleForm = ref(null)
const layerDom = ref(null)
const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  category: [{ required: true, message: '请输入文章分类', trigger: 'blur' }],
  sortNum: [{ required: true, message: '请输入排序序号', trigger: 'blur' }],
}
let form = ref({
  id: null,
  title: null,
  content: null,
  pictureId: null,
  pictureUrl: null,
  category: null,
  sortNum: null,
  createTime: null,
  updateTime: null,
  delFlag: null,
})

/************************************数据回显************************************************/
if (props.layer.row) {
  if (props.layer.row) {
    let source = props.layer.row
    Object.keys(form.value).forEach(k => k in source && (form.value[k] = source[k]));
  }
}

/************************************上传图片************************************************/
const formLoading = ref(false);
const files = ref([]);
const beforeUpload = (file) => {
  formLoading.value = true;
  if (file.size > 5 * 1024 * 1024) {
    MessagePlugin.warning('上传的图片不能大于5M');
    return false;
  }
  return true;
};
const requestMethod = async (file) => {
  console.log('[ file ] >', file)
  form.file = file.raw;
  form.value.attachName = file.raw.name;
  form.value.fileType = file.raw.type;
  console.log('[ form1 ] >', form)
  try {
    const res = await upload(form);
    if (res.code === 0) {
      form.value.pictureUrl = res.data;
      console.log('[ pictureUrl ] >', form.pictureUrl)
      console.log('[ form2 ] >', form)
      MessagePlugin.success('上传成功');
      formLoading.value = false;
      return new Promise((resolve) => {
        resolve({ status: 'success', response: { url: form.pictureUrl } });
      });
    }
    MessagePlugin.success(`上传失败:${res.msg}`);
    return new Promise((resolve) => {
      resolve({ status: 'fail', error: '上传失败' });
    });
  } catch (er) {
    MessagePlugin.success(`上传失败:${er}`);
    return new Promise((resolve) => {
      // resolve 参数为关键代码
      resolve({ status: 'fail', error: '上传失败' });
    });
  }
};

/************************************定义事件************************************************/
//提交按钮事件
let submit = () => {
  if (ruleForm) {
    ruleForm.value.validate((valid) => {
      if (valid) {
        let params = form.value
        if (props.layer.row) {
          updateForm(params)
        } else {
          addForm(params)
        }
      } else {
        return false;
      }
    });
  }
}

let updateForm = (params) => {
  updateAPI(params)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '编辑成功'
      })
      emit('getTableData', false)
      layerDom && layerDom.value.close()
    })
}

let addForm = (params) => {
  addAPI(params)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '新增成功'
      })
      emit('getTableData', true)
      layerDom && layerDom.value.close()
    })
}

/************************************文章富文本处理************************************************/
// 编辑器配置
const editorOptions = {
  debug: 'info',
  modules: {
    toolbar: [
      [{ size: [false, "small", "large", "huge"] }],            // 字号
      [{ header: [false, 1, 2, 3, 4, 5, 6] }],                  // 标题
      [{ color: [] }, { background: [] }],                      // 字体颜色、文本突出显示颜色
      ["bold", "italic", "underline", "strike"],                // 加粗、倾斜、下划线、删除线
      ["blockquote"],                                           // 块引用
      [{ script: "sub" }, { script: "super" }],                 // 下标、上标
      [{ list: "ordered" }, { list: "bullet" }],                // 有序、无序列表
      [{ indent: "-1" }, { indent: "+1" }],                     // 减少缩进量、增加缩进量
      [{ align: [] }],                                          // 对齐、左对齐、居中、右对齐、两端对齐
      ["link", "image", "video"],                       // 链接、图片、视频
      ["clean"],                                                // 清除样式
    ]
  },
  placeholder: '请输入内容~'
}
// 字典初始化start
const busTypeList = ref([]);
const initDicts = async () => {
  const res = await dicVals('bus_type');
  busTypeList.value = res.data;
  console.log('[ busTypeList ] >', busTypeList)
};
// 字典初始化end

/************************************生命周期************************************************/
//获取表格数据
onMounted(async () => {
  // vue的api
  await initDicts();
});
</script>

<template>
  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
      <el-form-item label="文章标题：" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类：" prop="category">
        <el-select v-model="form.category" placeholder="请选择文章分类">
          <el-option v-for="item in busTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序序号：" prop="sortNum">
        <el-input type="number" v-model="form.sortNum" placeholder="请输入排序序号"></el-input>
      </el-form-item>
      <el-form-item label="上传图片：" prop="fileName">
        <t-image v-if="form.pictureUrl" :src="form.pictureUrl" mode="aspectFill" width="72" height="72"
          aria-label="图片" />
        <t-upload v-model="files" :tips="'上传文件大小在 5M 以内'" theme="custom" :before-upload="beforeUpload"
          :request-method="requestMethod">
          <t-button theme="default" variant="outline" :style="{ marginTop: '10px' }">
            <template #icon> <t-icon name="photo"></t-icon> </template>上传图片</t-button>
        </t-upload>
      </el-form-item>
      <el-form-item label="文章内容：" prop="content">
        <div class="editor-container">
          <QuillEditor v-model:content="form.content" contentType="html" theme="snow" :options="editorOptions" />
        </div>
        <!-- <el-input v-model="form.content" placeholder="请输入文章内容"></el-input> -->
      </el-form-item>
    </el-form>
  </Layer>
</template>

<style scoped lang="scss">
.el-input-number--large {
  line-height: 38px;
  width: 230px;
}
</style>

<style lang="scss" scoped>
.editor-container {
  height: 600px;
  width: 120%;
  margin-bottom: 60px;
}

.editor-container {
  ::v-deep {
    .ql-editor {
      min-height: 600px;
      max-height: 1000px;
    }

    .ql-snow.ql-toolbar {
      .ql-picker.ql-header {
        width: 70px;

        .ql-picker-label::before,
        .ql-picker-item::before {
          content: '普通';
        }

        .ql-picker-label[data-value='1']::before,
        .ql-picker-item[data-value='1']::before {
          content: '标题一';
        }

        .ql-picker-label[data-value='2']::before,
        .ql-picker-item[data-value='2']::before {
          content: '标题二';
        }

        .ql-picker-label[data-value='3']::before,
        .ql-picker-item[data-value='3']::before {
          content: '标题三';
        }

        .ql-picker-label[data-value='4']::before,
        .ql-picker-item[data-value='4']::before {
          content: '标题四';
        }

        .ql-picker-label[data-value='5']::before,
        .ql-picker-item[data-value='5']::before {
          content: '标题五';
        }

        .ql-picker-label[data-value='6']::before,
        .ql-picker-item[data-value='6']::before {
          content: '标题六';
        }
      }

      .ql-picker.ql-size {
        width: 70px;

        .ql-picker-label::before,
        .ql-picker-item::before {
          content: '普通';
        }

        .ql-picker-label[data-value='small']::before,
        .ql-picker-item[data-value='small']::before {
          content: '小';
        }

        .ql-picker-label[data-value='large']::before,
        .ql-picker-item[data-value='large']::before {
          content: '中';
        }

        .ql-picker-label[data-value='huge']::before,
        .ql-picker-item[data-value='huge']::before {
          content: '大';
        }
      }
    }

    .ql-snow .ql-tooltip::before {
      content: '链接';
    }

    .ql-snow .ql-tooltip a.ql-action::after {
      content: '编辑';
    }

    .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
      content: '保存';
    }

    .ql-snow .ql-tooltip a.ql-remove::before {
      content: '移除';
    }
  }
}
</style>